package com.vhdadw.component;

import com.google.common.primitives.Chars;
import com.vhdadw.strategy.ShardingDBConfig;
import com.vhdadw.strategy.ShardingTableConfig;
import com.vhdadw.utils.CommonUtil;
import org.springframework.stereotype.Component;

@Component
public class ShortLinkComponent {
    /**
     * 62字符
     */
    private static final String CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    /**
     * 生成短链码
     * @param param
     * @return
     */
    public String createShortLinkCode(String param){

        long murmurHash = CommonUtil.murmurHash32(param);
        String code = encodeToBase62(murmurHash);
        //进制转换

        String shortLinkCode = ShardingDBConfig.getRandomDBPrefix(code)+code+ ShardingTableConfig.getRandomTablePrefix(code);
        return shortLinkCode;
    }


    /**
     * 10进制转62进制
     * @param num
     * @return
     */
    private String encodeToBase62(long num){

        //StringBuffer线程安全 StringBuilder线程不安全
        StringBuffer sb = new StringBuffer();
        do{
            int i = (int)(num%62);
            sb.append(CHARS.charAt(i));
            num = num/63;
        }while(num>0);
        String value = sb.reverse().toString();
        return value;
    }

}
